<template>
    <div class="container">
        <van-nav-bar
                :title="title"
                :right-text="rightText"
                left-arrow
                @click-left="$router.goBack()"
                @click-right="onClickRight"
        ></van-nav-bar>
        <div class="map-view">
            <el-amap ref="shareMap" vid="shareAmap" :amap-manager="amapManager" :zoom="zoom"
                     :plugin="plugin" :events="events">
            </el-amap>
            <template v-if="type == 0">
                <div class="wave solid warning ripple mapper">
                    <div class="circle"></div>
                    <div class="circle"></div>
                    <div class="circle"></div>
                </div>
                <div class="user">
                    <i class="iconfont icon-ziyuan"></i>
                </div>
            </template>
            <driver-info v-show="type > 0" ref="driverInfo" :driver-id="driverData.order.driverid"
                         class="driver-info-bottom"></driver-info>

        </div>
    </div>
</template>

<script>
    /* eslint-disable no-console,no-undef */


    import {AMapManager} from 'vue-amap';
    import DriverInfo from "../components/DriverInfo";

    let amapManager = new AMapManager();

    export default {
        name: "ShareMapView",
        components: {DriverInfo},
        data() {
            return {
                amapManager,
                orderNo: "",
                driverStar: 3,
                startLocation: {
                    lat: 0,
                    lng: 0
                },
                type: 0,
                targetLocation: {
                    lat: 0,
                    lng: 0
                },
                driverData: {
                    order: {
                        driverid: ""
                    }
                },
                locationTimer: null,
                events: {
                    init: (o) => {
                        let map = this.$refs.shareMap.$$getInstance();
                        map.setStatus({
                            dragEnable: false,
                            zoomEnable: false,
                            rotateEnable: false
                        })
                        // console.log(o.getCenter())
                        // console.log()
                        // o.getCity(result => {
                        //     console.log(result)
                        // })
                    },
                    'moveend': () => {
                    },
                    'zoomchange': () => {
                    },

                },
                title: "等待接单",
                rightText: "取消订单",
                plugin: ['AMap.Driving'],
                zoom: 16,
            }
        },
        beforeRouteEnter(to, from, next) {
            next(vm => {
                vm.orderNo = vm.$route.query.orderNo;
                let start = vm.$route.query.start;
                if (start) {
                    let split = start.split(',');
                    vm.startLocation = {lat: split[1], lng: split[0]}
                }
                let target = vm.$route.query.target;
                if (target) {
                    let tagetSplit = target.split(',');
                    vm.targetLocation = {lat: tagetSplit[1], lng: tagetSplit[0]}
                }
                let type = vm.$route.query.type;
                if (type != null) {
                    vm.type = parseInt(type);

                    switch (vm.type) {
                        case 0:
                            vm.rightText = '取消订单'
                            vm.title = '等待接单'
                            break;
                        case 1:
                            vm.rightText = '取消订单'
                            vm.title = '等待接驾'
                            break;
                        case 2:
                            vm.title = '行程中'
                            vm.rightText = ''
                            break;
                    }
                }

                window.eventBus.$on('onShareOrderCancelByUserResult', vm.onCancelResult)
                window.eventBus.$on("onDriverGetShareOrderResult", vm.onDriverGetOrder)
                window.eventBus.$on("onShareDriverLocationUpdate", vm.onDriverUpdateLocation)
                window.eventBus.$on("onShareUserStart", vm.onShareUserStart)

                vm.initTimer();
            })
        },

        beforeRouteLeave(to, from, next) {
            window.eventBus.$off('onShareOrderCancelByUserResult', this.onCancelResult);
            window.eventBus.$off("onDriverGetShareOrderResult", this.onDriverGetOrder);
            window.eventBus.$off("onShareDriverLocationUpdate", this.onDriverUpdateLocation)
            window.eventBus.$off("onShareUserStart", this.onShareUserStart)

            this.stopTimer();
            next();
        },

        methods: {
            onShareUserStart(data) {
                this.type = 2;
            },

            onDriverGetOrder(data) {
                this.type = 1;
                this.driverData.order.driverid = data.driverid
            },

            drawRoute(route) {
                let map = this.$refs.shareMap.$$getInstance();
                let path = this.parseRouteToPath(route)

                let icon = new AMap.Icon({
                    size: new AMap.Size(49, 32.66),
                    imageSize: new AMap.Size(49, 32.66),
                    image: '/icon_car_share.png'
                });
                //
                //
                // let marker = new AMap.Marker({
                //     position: new AMap.LngLat(data.lng, data.lat),
                //     offset: new AMap.Pixel(-24.5, -16.33),
                //     icon: icon,
                //     angle: data.degree
                // });

                let startMarker
                if (this.type == 2) {
                    startMarker = new AMap.Marker({
                        position: path[0],
                        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
                        map: map
                    })
                } else {
                    startMarker = new AMap.Marker({
                        position: path[0],
                        icon: icon,
                        offset: new AMap.Pixel(-24.5, -16.33),
                        map: map
                    })
                }

                let endMarker = new AMap.Marker({
                    position: path[path.length - 1],
                    icon: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png',
                    map: map
                })

                let routeLine = new AMap.Polyline({
                    path: path,
                    isOutline: true,
                    outlineColor: '#ffeeee',
                    borderWeight: 2,
                    strokeWeight: 5,
                    strokeColor: '#0091ff',
                    lineJoin: 'round'
                })

                routeLine.setMap(map)

                // 调整视野达到最佳显示区域
                map.setFitView([startMarker, endMarker, routeLine])
                map.setStatus({
                    dragEnable: true,
                    zoomEnable: true,
                    rotateEnable: true
                })
            },
            parseRouteToPath(route) {
                let path = []

                for (let i = 0, l = route.steps.length; i < l; i++) {
                    let step = route.steps[i]

                    for (let j = 0, n = step.path.length; j < n; j++) {
                        path.push(step.path[j])
                    }
                }
                return path
            },

            drivePath() {
                if (this.type > 0) {
                    let map = this.$refs.shareMap.$$getInstance();
                    if (map) {
                        let data = this.driverData;
                        let driving = new AMap.Driving({
                            // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
                            policy: AMap.DrivingPolicy.LEAST_TIME
                        })
                        if (driving) {
                            let startLngLat = [data.lng, data.lat]
                            let endLngLat = [this.startLocation.lng, this.startLocation.lat]
                            if (this.type == 2) {
                                startLngLat = [this.startLocation.lng, this.startLocation.lat]
                                endLngLat = [this.targetLocation.lng, this.targetLocation.lat]
                            }

                            driving.search(startLngLat, endLngLat, (status, result) => {
                                // 未出错时，result即是对应的路线规划方案
                                console.log(result);
                                if (status === 'complete') {
                                    if (result.routes && result.routes.length) {
                                        // 绘制第一条路线，也可以按需求绘制其它几条路线
                                        this.drawRoute(result.routes[0])
                                        console.log('绘制驾车路线完成')
                                    }
                                } else {
                                    console.error('获取驾车数据失败：' + result)
                                }
                            })
                        }
                    }

                }
            },

            onDriverUpdateLocation(data) {
                this.driverData = data;
                this.drivePath();
            },
            initTimer() {
                this.locationTimer = setInterval(() => {
                    let socket = this.$store.state.socket
                    if (socket) {
                        let uid = this.$store.state.userInfo.passenger.passengerid
                        socket.send(JSON.stringify({mid: 2021, data: {uid: uid, orderNo: this.orderNo}}))
                    }
                }, 2000)
            },
            stopTimer() {
                clearInterval(this.locationTimer);
            },
            onCancelResult(result) {
                if (result.state) {
                    this.$toast.success(result.message);
                    this.$router.goBack();
                } else {
                    this.$toast(result.message);
                }
            },
            onClickRight() {
                if (this.type <= 1){
                    this.$dialog.confirm({
                        title: "提示",
                        message: "您确定取消订单吗？"
                    }).then(() => {
                        let socket = this.$store.state.socket;
                        if (socket) {
                            socket.send(JSON.stringify({mid: 2007, data: {orderNo: this.orderNo}}))
                        }
                    }).catch(error => {

                    })
                }

            }
        }
    }
</script>

<style scoped lang="less">
    .container {
        height: 100%;
        .map-view {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: calc(100% - 46px);
            position: relative;
            .el-vue-amap-container {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                z-index: 999;
            }
        }
    }

    .mapper {
        width: 300px;
        height: 300px;
        left: 0;
        top: 0;
        position: absolute;
        z-index: 1000;
    }

    .user {
        position: absolute;
        z-index: 1001;
        width: 44px;
        height: 44px;
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-left: 4px;
        margin-top: 4px;
        justify-content: center;
        .icon-ziyuan {
            font-size: 18px;
            color: #0aa4f3;
        }
    }

    .driver-info-bottom {
        position: absolute;
        z-index: 1001;
        bottom: 16px;
    }

    .wave {
        position: relative;
        width: 300px;
        height: 300px;
        text-align: center;
        line-height: 300px;
        font-size: 28px;
    }

    .wave .circle {
        position: absolute;
        border-radius: 50%;
        opacity: 0;
    }

    /* 波纹效果 */
    .wave.ripple .circle {
        width: calc(100% - 6px); /* 减去边框的大小 */
        height: calc(100% - 6px); /* 减去边框的大小 */
        border: 3px solid #fff;
    }

    .wave.ripple .circle:first-child {
        animation: circle-opacity 2s infinite;
    }

    .wave.ripple .circle:nth-child(2) {
        animation: circle-opacity 2s infinite;
        animation-delay: .3s;
    }

    .wave.ripple .circle:nth-child(3) {
        animation: circle-opacity 2s infinite;
        animation-delay: .6s;
    }

    .wave.ripple.danger {
        color: #f37c18;
    }

    .wave.ripple.danger .circle {
        border-color: #f37c18;
    }

    .wave.ripple.warning {
        color: orange;
    }

    .wave.ripple.warning .circle {
        border-color: orange;
    }

    /* 波动效果 */
    .wave.solid .circle {
        width: 100%;
        height: 100%;
        background: #fff;
    }

    .wave.solid .circle:first-child {
        animation: circle-opacity 2s infinite;
    }

    .wave.solid.danger {
        color: red;
    }

    .wave.solid.danger .circle {
        background: red;
    }

    .wave.solid.warning {
        color: orange;
    }

    .wave.solid.warning .circle {
        background: orange;
    }

    @keyframes circle-opacity {
        from {
            opacity: 1;
            transform: scale(0);
        }
        to {
            opacity: 0;
            transform: scale(1);
        }
    }
</style>